﻿using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TcpServiceForWebApi.Plugins
{
    public class MyTcpPlugin : PluginBase, ITcpConnectedPlugin<ISocketClient>
    {
        private ILogger<MyTcpPlugin> m_logger;

        public MyTcpPlugin(ILogger<MyTcpPlugin> logger)
        {
            this.m_logger = logger;
        }

        public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e)
        {
            this.m_logger.LogInformation("客户端连接");

            //receiver可以复用，不需要每次接收都新建
            using (var receiver = client.CreateReceiver())
            {
                while (true)
                {
                    //receiverResult必须释放
                    using (var receiverResult = await receiver.ReadAsync(CancellationToken.None))
                    {
                        if (receiverResult.IsClosed)
                        {
                            //断开连接了
                            //await Console.Out.WriteLineAsync("链接已断开！");
                            this.m_logger.LogInformation($"链接已断开！");
                            return;
                        }

                        //从服务器收到信息。
                        var mes = Encoding.UTF8.GetString(receiverResult.ByteBlock.Buffer, 0, receiverResult.ByteBlock.Len);
                        //await Console.Out.WriteLineAsync(mes);
                        //client.Logger.Info($"客户端接收到信息：{mes}");
                        this.m_logger.LogInformation($"服务端接收到信息：{mes}");
                        
                        //如果是适配器信息，则可以直接获取receiverResult.RequestInfo;

                    }
                }
                
            }

            await e.InvokeNext();
        }
       

    }
}